package com.mlnx.bluwifi.service.iml;

import com.mlnx.bluwifi.manager.SpoPolicy;
import com.mlnx.bluwifi.pojo.DataCache;
import com.mlnx.bluwifi.service.WifiBluService;
import com.mlnx.common.utils.MyLog;
import com.mlnx.data.entity.BpInfo;
import com.mlnx.data.entity.SpoInfo;
import com.mlnx.device.entity.Device;
import com.mlnx.stream.service.DeviceBroadcastService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

/**
 * Created by amanda.shan on 2019/11/29.
 */
public class WifiBluPushService extends BaseWifiBluService implements WifiBluService {

    MyLog log = MyLog.getLog(getClass());

    @Autowired
    private DeviceBroadcastService deviceBroadcastService;

    @PostConstruct
    public void init() {
        log.info("启动WifiBluPushService 新的推送服务");
    }

    @Override
    public void broadCastSpo(String deviceId, int spo, int heart) {

        if (SpoPolicy.getInstance().judge(deviceId, spo)) {

            SpoInfo spoInfo = new SpoInfo();
            spoInfo.setDeviceId(deviceId);
            spoInfo.setResultHeart(heart);
            spoInfo.setResultSPO(spo);
            spoInfo.setTime(System.currentTimeMillis());


            Device device = getDevice(deviceId);
            if (device.getPatientId() == null || device.getPatientId() == 0) {
                log.error("{} 血氧设备未绑定患者", deviceId);
            }
            spoInfo.setPatientId(device.getPatientId());
            DataCache dataCache= SpoPolicy.getInstance().getDataCache(deviceId);
            dataCache.setCurrentTime(System.currentTimeMillis());
            dataCache.setSpoInfo(spoInfo);
            SpoPolicy.getInstance().setDataCache(dataCache,deviceId);
//            SpoPolicy.getInstance().setSpoInfo(spoInfo, deviceId);

            if (spo >= 0 && spo <= 100) {
                deviceBroadcastService.castSpoInfo(spoInfo);
            }
        }
    }

    @Override
    public void broadCastBp(String deviceId, int sbp, int dbp, int heart) {

        BpInfo bpInfo = new BpInfo();
        bpInfo.setDeviceId(deviceId);
        bpInfo.setSbp(sbp);
        bpInfo.setDbp(dbp);
        bpInfo.setHeart(heart);
        bpInfo.setTime(System.currentTimeMillis());

        Device device = getDevice(deviceId);
        if (device.getPatientId() == null || device.getPatientId() == 0) {
            log.error("{} 血压设备未绑定患者", deviceId);
        }
        bpInfo.setPatientId(device.getPatientId());
        DataCache dataCache= SpoPolicy.getInstance().getDataCache(deviceId);
        dataCache.setCurrentTime(System.currentTimeMillis());
        dataCache.setBpInfo(bpInfo);
        SpoPolicy.getInstance().setDataCache(dataCache,deviceId);
        deviceBroadcastService.castBpInfo(bpInfo);

    }
}
